package me.yricky.cov_spectrum.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.yricky.cov_spectrum.model.ApiModel
import me.yricky.cov_spectrum.model.beans.CollectionItem
import me.yricky.cov_spectrum.model.beans.CountryData

class CollectionViewModel:ViewModel() {

    private val _list:MutableStateFlow<List<CollectionItem>> = MutableStateFlow(emptyList())
    val list = _list.asStateFlow()


    private val _stat:MutableStateFlow<LoadingStatus> = MutableStateFlow(LoadingStatus.Loading)
    val loadingStatus = _stat.asStateFlow()
    fun reloadList(){
        viewModelScope.launch {
            _stat.value = LoadingStatus.Loading
            _list.value = withContext(Dispatchers.IO){
                try{
                    ApiModel.getCollectionItem().getOrThrow().also {
                        _stat.value = LoadingStatus.Success
                    }
                }catch (e:Throwable){
                    _stat.value = LoadingStatus.Error(e)
                    emptyList()
                }
            }
        }
    }

    init {
        reloadList()
    }
}